package com.zhilifang.modules.zlf.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.zhilifang.common.utils.R;
import com.zhilifang.modules.zlf.entity.ImgUpload;
import com.zhilifang.modules.zlf.entity.Product;
import com.zhilifang.modules.zlf.entity.ProductType;
import com.zhilifang.modules.zlf.service.impl.ProductServiceImpl;
import com.zhilifang.modules.zlf.service.impl.ProductTypeServiceImpl;
import com.zhilifang.modules.zlf.utils.Pager;
import com.zhilifang.modules.zlf.utils.QueryString;
import com.zhilifang.modules.zlf.utils.Result;
import com.zhilifang.modules.zlf.utils.Utils;

/**
 * Controller 后台首页>>发布产品Controller
 */
@Controller
@RequestMapping("/productController")
public class ProductController {

	@Autowired
	private ProductServiceImpl productServiceImpl;
	
	@Autowired
	private ProductTypeServiceImpl productTypeServiceImpl;
	

	
	
	
	/**
	 * 首页展示查询所有产品，根据类型id查询，id为999的的时候是所有
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selecProductListr", method = RequestMethod.POST)
	@ResponseBody
	public List<Product> selecProductListr(Integer id){
		List<Product> list = productServiceImpl.selecProductListr(999);	
		return list;
	}
	
	/**
	 * 产品内容列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selectProductPageQueryString", method = RequestMethod.POST)
	@ResponseBody
	public Pager<Product> selectProductPageQueryString(QueryString queryString){
		Pager<Product> pager = new Pager<Product>();
		if(!"".equals(queryString.getReady01())&&queryString.getReady01()!=null){
			queryString.setReady01("%"+queryString.getReady01()+"%");  //内容标题
		}
		if(!"".equals(queryString.getReady02())&&queryString.getReady02()!=null){
			queryString.setReady02(queryString.getReady02());  //产品分类
		}
		List<Product> list = productServiceImpl.selectProductPageQueryString(queryString);
		if (list != null&&!list.isEmpty()) {
			pager=new Pager<Product>(queryString.getCurrentPage(),queryString.getPageSize(), list);
		}
		return pager;
	}
	
	
	
	/**
	 * 删除&批量删除产品
	 * 
	 * @return
	 */
	@RequestMapping(value = "/deleteProductIds", method = RequestMethod.POST)
	@ResponseBody
	public Result deleteProductIds(int [] ids){
		Result result = new Result();
		productServiceImpl.deleteProductIds(ids);	
		result.setMessage("删除成功");
		result.setState("200");
		return result;
	}

	
	/**
	 * 查询详情
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selectProductById", method = RequestMethod.POST)
	@ResponseBody
	public Product selectProductById(int  id){
		Product  result = productServiceImpl.selectProductById(id);
		return result;
	}

	/**
	 * 发布产品&&修改产品
	 * 
	 * @return
	 */
	@RequestMapping(value = "/insertUpdateProduct", method = RequestMethod.POST)
	@ResponseBody
	public Result insertUpdateProduct(Product product){
		Result result = new Result();
		if(product.getId()!=null){
			productServiceImpl.updateByPrimaryKeySelective(product);
			result.setMessage("修改成功");
			result.setState("200");
		}else{
			productServiceImpl.insertSelective(product);
			result.setMessage("添加成功");
			result.setState("200");
		}
		
		return result;
	}
	
	
	/**
	 * 产品接收图片上传
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	 @RequestMapping(value="/imgUploadProduct")
    @ResponseBody
    public String  imgUploadProduct(MultipartFile upfile,String type) throws IllegalStateException, IOException {
		if(type==""||type==null){
			type ="product";
		}
		String path = Utils.isLinux(type);  		//判断当前系统类型，根据系统类型存放文件
		//创建图片文件夹存放图片
        File fileDir = new File(path);
        //判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        String fileName = returnPrefixSuffixName(upfile.getOriginalFilename());
        fileDir = new File(path+fileName);
        upfile.transferTo(fileDir);//实现文件的上传
        Map<String, Object> result = new HashMap<String, Object>();
        
        result.put("name", upfile.getOriginalFilename());// 新的文件名
        result.put("originalName", upfile.getOriginalFilename());// 原始文件名
        result.put("size", upfile.getSize());
        result.put("state", "SUCCESS");
        result.put("url", "/localImg/"+type+"/"+fileName);// 展示图片的请求url
        String jStr = JSON.toJSONString(result);
        return jStr;
    }
	
	/**
	 * 接收图片上传
	 * 
	 * @return
	 * @throws IOException 
	 * @throws IllegalStateException 
	 */
	@RequestMapping(value = "/imgUpload", method = RequestMethod.POST)
	@ResponseBody
	public ImgUpload imgUpload(@RequestParam("img") MultipartFile list , String type) throws IllegalStateException, IOException{
		ImgUpload result = new ImgUpload();
		String[] data = new String[5];
		if(type==""||type==null){
			type ="product";
		}
		String path = Utils.isLinux(type);  		//判断当前系统类型，根据系统类型存放文件
		//创建图片文件夹存放图片
        File fileDir = new File(path);
        //判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        String fileName = returnPrefixSuffixName(list.getOriginalFilename());
        fileDir = new File(path+fileName);
        list.transferTo(fileDir);//实现文件的上传
		data[0]="/localImg/"+type+"/"+fileName;
        result.setErrno("0");
        result.setData(data);
		return result;
	}
	
	/**
	 * 随机生成文件名称
	 * 名称当前时间+随机数+文件后缀名
	 * 
	 */
	public String returnPrefixSuffixName(String fileName) {
		long time = new Date().getTime() + Math.round(Math.random() * 1000);  //生成随机数
        String prefix = time + "";  //类型转换
		String[] strArray = fileName.split("\\.");
        int suffixIndex = strArray.length -1;
		String suffix =  "."+strArray[suffixIndex];  //生成文件后缀名
		return prefix+suffix;
	}
	
	
	/** 
	* 判断是linux系统还是其他系统 
	* 如果是Linux系统，返回true，否则返回false 
	*/ 
	public static boolean isLinux() { 
		return System.getProperty("os.name").toLowerCase().indexOf("linux") >= 0; 
	}
	
	
	@GetMapping("selecctListr")
	@ResponseBody
	public R selectListr(){
		 Map<String, Object> map = new HashMap<>();
		Result result =new Result();
		List<Product> list = productServiceImpl.selecProductListr(999);	
		result.setData(list);
		result.setMessage("sessse");
		map.put("list", list);
		result.setState("200");
		return R.ok().put("list", list);
	}
	
	
	/**
	 * 查询所有产品信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selecProductListrAll", method = RequestMethod.POST)
	@ResponseBody
	public List<Product> selecProductListrAll(String name,String ids){
		if(!"".equals(name)&&name!=null){
			name = "%"+name+"%";  //模糊查询
		}
		String[] idArray = null;
		if(!"".equals(ids)&&ids!=null){
			idArray  = ids.split(",");
		}
		List<Product> list = productServiceImpl.selecProductListrAll(name,idArray);	
		return list;
	}
	
	/**
	 * 查询所有相关产品信息
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selecProductInIds", method = RequestMethod.POST)
	@ResponseBody
	public List<Product> selecProductInIds(String ids){
		String[] idArray  = ids.split(",");
		List<Product> list = productServiceImpl.selecProductInIds(idArray);
		return list;
	}
	
	
	/**
	 * 查询产品所有类型列表
	 * 
	 * @return
	 */
	@RequestMapping(value = "/selectProductTypeListAll", method = RequestMethod.POST)
	@ResponseBody
	public List<ProductType> selectProductTypeListAll(){
		return productTypeServiceImpl.selectListAll();
	}
	
	
}
